﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace SharpWebSocket.Protocol
{
    internal sealed class Draft10HandShakeResponse
    {
        /*
         * 
         * BEGIN RESPONSE SAMPLE
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: {0}
WebSocket-Location: ws://{1}
           END RESPONSE SAMPLE
         *  
         */

        internal Draft10HandShakeResponse( Draft10HandShakeRequest request )
        {
            if (request == null)
            {
                throw new ArgumentNullException( "request" );
            }
            HandShakeRequest = request;

            SecWebSocketAccept = SHA1AndBase64( request.SecWebSocketKey + Draft10Environment.MAGIC_KEY );
        }

        private Draft10HandShakeRequest HandShakeRequest
        {
            get;
            set;
        }

        public string SecWebSocketAccept
        {
            get;
            set;
        }

        public string HandShakeResponse
        {
            get
            {
                return string.Format( @"HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: {0}
WebSocket-Location: ws://{1}

", SecWebSocketAccept, HandShakeRequest.Host );
            }
        }

        public SocketError CompleteHandShake( Socket socket )
        {
            var data = Encoding.UTF8.GetBytes( HandShakeResponse );
            SocketError err = SocketError.Success;
            socket.Send( data, 0, data.Length, SocketFlags.None, out err );
            return err;
        }

        

        internal static string SHA1AndBase64( string str )
        {
            var crypto = System.Security.Cryptography.SHA1.Create();
            byte[] computeResult = crypto.ComputeHash( Encoding.ASCII.GetBytes( str ) );
            return Convert.ToBase64String( computeResult );
            // return Encoding.ASCII.GetString(  );
        }
    }
}
